import java.util.Arrays;
import java.util.Stack;

/*
 * @lc app=leetcode.cn id=42 lang=java
 *
 * [42] 接雨水
 *
 * https://leetcode.cn/problems/trapping-rain-water/description/
 *
 * algorithms
 * Hard (61.05%)
 * Likes:    3506
 * Dislikes: 0
 * Total Accepted:    497.3K
 * Total Submissions: 813.5K
 * Testcase Example:  '[0,1,0,2,1,0,1,3,2,1,2,1]'
 *
 * 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图，计算按此排列的柱子，下雨之后能接多少雨水。
 * 
 * 
 * 
 * 示例 1：
 * 
 * 
 * 
 * 
 * 输入：height = [0,1,0,2,1,0,1,3,2,1,2,1]
 * 输出：6
 * 解释：上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图，在这种情况下，可以接 6 个单位的雨水（蓝色部分表示雨水）。 
 * 
 * 
 * 示例 2：
 * 
 * 
 * 输入：height = [4,2,0,3,2,5]
 * 输出：9
 * 
 * 
 * 
 * 
 * 提示：
 * 
 * 
 * n == height.length
 * 1 <= n <= 2 * 10^4
 * 0 <= height[i] <= 10^5
 * 
 * 
 */

// @lc code=start
class Solution {

    public int trap1(int[] height) {
        int n = height.length;
        Stack<Integer> stack = new Stack<>();
        int i = 0, maxBotWater = 0, maxWater = 0;
        while (i < n) {
            if (!stack.isEmpty() && height[i] > height[stack.peek()]) {
                int bot = stack.pop();
                maxBotWater = stack.isEmpty() ? 0
                        : Math.min(height[i] - height[bot], height[stack.peek()]) * (i - stack.peek() - 1);
                maxWater += maxBotWater;
            } else {
                stack.push(i++);
            }

        }
        return maxWater;
    }

    public int trap(int[] height) {
        // min(max(height[0, i]), max(height[i, end])) - height[i]
        int res = 0;
        int[] lmax = new int[height.length], rmax = new int[height.length];
        lmax[0] = height[0];
        rmax[height.length - 1] = height[height.length - 1];
        for (int j = 1; j < height.length; j++) {
            lmax[j] = Math.max(height[j], lmax[j - 1]);
        }
        for (int j = height.length - 2; j >= 0; j--) {
            rmax[j] = Math.max(height[j], rmax[j + 1]);
        }
        for (int i = 0; i < height.length; i++) {
            int bolt = Math.min(lmax[i], rmax[i]) - height[i];
            if (bolt <= 0)
                continue;
            res += bolt;
        }
        return res;
    }
}
// @lc code=end
